package cn.getech.data.development.utils.sched;

import cn.getech.data.development.config.properties.OozieConfig;
import cn.getech.data.development.constant.WorkFlowType;
import cn.getech.data.development.entity.JobRunHistory;
import cn.getech.data.development.feign.JobRestFeignApi;
import cn.getech.data.development.mapper.JobRunHistoryMapper;
import cn.getech.data.intelligence.common.utils.DateUtils;
import cn.getech.data.intelligence.common.utils.R;
import cn.getech.job.center.vo.JobBeanDataVO;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 作业流依赖添加补回调措施
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "data-development.websocket-open", havingValue = "true")
public class AddSyncUtils {

    @Autowired
    private JobRunHistoryMapper jobRunHistoryMapper;

    @Autowired
    private JobRestFeignApi jobRestFeignApi;


    /***
     * 每3s推送一次数据
     */
   // @Scheduled(cron = "0/15 * * * * ?")
    private void addSync() {
        //查询到所有的节点是运行中的任务节点并且其任务不是运行中
        //由于作业流依赖，报错导致的killed，从而不会调数据
        List<JobRunHistory> jobRunHistories = jobRunHistoryMapper.selectAllRunningList();
        if (CollectionUtil.isNotEmpty(jobRunHistories)) {
            for (JobRunHistory jobRunHistory : jobRunHistories) {
                try {
                    //回调处理日志信息
                    // {"jobName":"180/426","number":"16","stat_date":"2020-02-26 15:34:00" }
                    String jobName = WorkFlowType.WORKFLOW.getCode() + "/" + jobRunHistory.getProcId() + "/" + jobRunHistory.getJobInfoId();
                    String oozieJobId = jobRunHistory.getOozieJobId();
                    String startTimeDate = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN);
                    JobBeanDataVO jobBeanDataVO = new JobBeanDataVO();
                    jobBeanDataVO.setJobName(jobName);
                    jobBeanDataVO.setOozieJobId(oozieJobId);
                    jobBeanDataVO.setStatDate(startTimeDate);
                    jobRestFeignApi.jobEnd(jobBeanDataVO);

                } catch (Exception e) {
                    log.error("重新启动对应的由于killed中断回调的bug的异常！error:{}", e.getMessage());
                }
            }
        }
    }

}
